<%--
  Created by IntelliJ IDEA.
  User: cjbi
  Date: 2018/4/6
  Time: 7:43
  空页面.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<!-- Content Header (Page header) -->
<section class="content-header" style="">
    <h1>
        账单管理
        <small>账单管理页面</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> 主页</a></li>
        <li><a href="#">账单管理</a></li>
        <li class="active">账单统计</li>
    </ol>
</section>

<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <!-- /.box-header -->
                <div class="box-body">
                    <div class="btn-group btn-group-sm" id="toolbar">
                        <!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
                        <div class="control-row">
                            <select name="chartType" id="chartType" style="height:26px;line-height:26px;}">
                                <option value="barChart">柱状图</option>
                                <option value="lineChart">折线图</option>
                                <option value="pieChart">饼形图</option>
                            </select>
                            <input type="text" id="SZtime" size="" style="height:26px;line-height:26px;">
                            <button class="" id="btnQuery" style="">搜索</button>
                        </div>
                    </div>

                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->

        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>

<div class="main_chart">
    <div id="chartArea" class="data display" style="min-height:500px;"></div>
</div>

<!-- detail Modal -->
<div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="detailModalLabel">账单详情</h4>
            </div>
            <div class="modal-body">
                <table id="billTable"></table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(function() {
        $( "#SZtime" ).datepicker({
            changeMonth: false,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'yy',
            onClose: function(dateText, inst) {
                let year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(year, 1, 1));
            }
        });
        let chartType = "lineChart";
        $("#btnQuery").click(function () {
            var dataEx = new Array(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
            //直接定义长度会产生空位，输出值为undefined
            //var yearMonthArr = new Array("","","","","","","","","","","","");
            var selectYear = $("#SZtime").val();
            var yearMonthArr = new Array(selectYear+"-01",+selectYear+"-02",+selectYear+"-03",+selectYear+"-04",+selectYear+"-05",+selectYear+"-06",+selectYear+"-07",+selectYear+"-08",+selectYear+"-09",+selectYear+"-10",+selectYear+"-11",+selectYear+"-12");
            var dataIn = new Array(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
            var deferred1 = $.ajax({
                type: 'post',
                url: 'billdata/getExpense',
                data:{
                    year: $("#SZtime").val()
                },
                dataType: 'json',
                async: false,
                success: function (result) {
                    let data = result.data;
                    console.log(data)
                    for (let i = 0; i < data.length; i++) {
                        const obj = data[i];
                        //yearMonthArr.push(obj.yearMonth);
                        var mon =parseInt(obj.yearMonth.substring(5));
                        yearMonthArr[mon-1] = obj.yearMonth;
                        //dataEx.push(obj.totalAmount);
                        dataEx[mon-1] = obj.totalAmount;
                    }
                    //getLineChart(monEx, dataEx);
                    //getBarChart(mon, dataMoney);
                    //getPieChartByMonth(mon, dataMoney);
                }
            })

            var deferred2 = $.ajax({
                type: 'post',
                url: 'billdata/getIncome',
                data:{
                    year: $("#SZtime").val()
                },
                dataType: 'json',
                async: false,
                success: function (result) {
                    let data = result.data;
                    console.log(data)
                    for (let i = 0; i < data.length; i++) {
                        const obj = data[i];
                        //yearMonthArr.push(obj.yearMonth);
                        let mon =parseInt(obj.yearMonth.substring(5));
                        yearMonthArr[mon-1] = obj.yearMonth;
                        //dataEx.push(obj.totalAmount);
                        dataIn[mon-1] = obj.totalAmount;
                        //dataIn.push(obj.totalAmount);
                    }
                    //getLineChart(monIn, dataIn);
                    //getBarChart(mon, dataMoney);
                    //getPieChartByMonth(mon, dataMoney);
                }
            })

            $.when(deferred1, deferred2).done(function(result1, result2) {
                //console.log(result1[0]);
                // console.log(result2[0]);
                //var _yearMonthArr = unique(yearMonthArr);
                chartType = $('#chartType').val();
                if(chartType==="lineChart"){
                    getLineChart(yearMonthArr,dataIn,dataEx);
                }else if(chartType==="barChart"){
                    getBarChart(yearMonthArr,dataIn,dataEx);
                }else if(chartType==="pieChart"){
                    getPieChartByMonth(yearMonthArr,dataIn,dataEx);
                }
                console.log(dataEx)
                console.log(dataIn)
                console.log(typeof(yearMonthArr[0]))

            }).fail(function() {
                console.log("获取数据失败");
            });
        })
    })


    $(document).ready(function () {
        let dataEx = new Array(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
        //直接定义长度会产生空位，输出值为undefined
        //var yearMonthArr = new Array("","","","","","","","","","","","");
        let currentYear = new Date().getFullYear();
        let yearMonthArr = new Array(currentYear+"-01",+currentYear+"-02",+currentYear+"-03",+currentYear+"-04",+currentYear+"-05",+currentYear+"-06",+currentYear+"-07",+currentYear+"-08",+currentYear+"-09",+currentYear+"-10",+currentYear+"-11",+currentYear+"-12");
        let dataIn = new Array(0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0);
        let deferred1 = $.ajax({
            type: 'post',
            url: 'billdata/getExpense',
            data:{
                year: new Date().getFullYear()
            },
            dataType: 'json',
            async: false,
            success: function (result) {
                let data = result.data;
                console.log(data)
                for (let i = 0; i < data.length; i++) {
                    const obj = data[i];
                    //yearMonthArr.push(obj.yearMonth);
                    let mon =parseInt(obj.yearMonth.substring(5));
                    yearMonthArr[mon-1] = obj.yearMonth;
                    //dataEx.push(obj.totalAmount);
                    dataEx[mon-1] = obj.totalAmount;
                }
                //getLineChart(monEx, dataEx);
                //getBarChart(mon, dataMoney);
                //getPieChartByMonth(mon, dataMoney);
            }
        })

        var deferred2 = $.ajax({
            type: 'post',
            url: 'billdata/getIncome',
            data:{
                year: new Date().getFullYear()
            },
            dataType: 'json',
            async: false,
            success: function (result) {
                let data = result.data;
                console.log(data)
                for (let i = 0; i < data.length; i++) {
                    const obj = data[i];
                    //yearMonthArr.push(obj.yearMonth);
                    console.log(data[i])
                    let mon =parseInt(obj.yearMonth.substring(5));
                    yearMonthArr[mon-1] = obj.yearMonth;
                    //dataEx.push(obj.totalAmount);
                    dataIn[mon-1] = obj.totalAmount;
                    //dataIn.push(obj.totalAmount);
                }
                //getLineChart(monIn, dataIn);
                //getBarChart(mon, dataMoney);
                //getPieChartByMonth(mon, dataMoney);
            }
        })

        $.when(deferred1, deferred2).done(function(result1, result2) {
            //console.log(result1[0]);
            // console.log(result2[0]);
            //var _yearMonthArr = unique(yearMonthArr);

            console.log(dataEx)
            console.log(dataIn)
            console.log(typeof(yearMonthArr[0]))
            getBarChart(yearMonthArr,dataIn,dataEx);
            //getBarChart(yearMonthArr,dataIn,dataEx);
            // getPieChartByMonth(yearMonthArr,dataIn,dataEx);

        }).fail(function() {
            console.log("获取数据失败");
        });


    })

    // 折线图
    function getLineChart(x, y1, y2) {
        var line = echarts.init(document.getElementById('chartArea'));
        line.clear();
        line.setOption({
            title: {
                text: '月度统计报告/折线图',
                left: 'center',
                textStyle: {
                    fontSize: 12,
                    // 若字体名称中带有空格，需要使用 `"` 包围
                    fontFamily: 'Arial',
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['收入金额', '支出金额'],
                left: 'left',
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                name: '月份',
                boundaryGap: false,//坐标轴两边留白
                data:x,
            },
            yAxis: {
                type: 'value',
                name: '金额（元）'
            },
            series: [
                //第一条折线图
                {
                    name: '收入金额',
                    type: 'line',
                    data:  y1,
                    // 区域填充样式
                    // areaStyle: {
                    //     normal: {
                    //         color: 'skyblue'
                    //     }
                    // },
                    // 线条样式
                    itemStyle: {
                            color: 'skyblue',
                            lineStyle: {
                                color: 'skyblue'
                        }
                    }
                },
                //第二条折线图
                {
                    name: '支出金额',
                    type: 'line',
                    data: y2,
                    // areaStyle: {
                    //     normal: {
                    //         color: 'red'
                    //     }
                    // },
                    itemStyle: {

                            color: 'red',
                            lineStyle: {
                                color: 'red'
                            }

                    }
                }
            ]
        })
    }

    var $billTable = $('#billTable');
    // 柱状图
    function getBarChart(x, y1, y2) {
        var bar = echarts.init(document.getElementById('chartArea'));
        bar.clear();
        bar.setOption({
            title: {
                text: '月度统计报告/柱状图',
                left: 'center',
                textStyle: {
                    fontSize: 12,
                    // 若字体名称中带有空格，需要使用 `"` 包围
                    fontFamily: 'Arial',
                    fontWeight: 'bold'
                }
            },
            //color: ['greenyellow'],
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'line'
                }
            },
            legend: {
                data: ['收入金额', '支出金额'],
                left: 'left'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    name: '月份',
                    data: x,
                    axisTick: {
                        alignWithLabel: true
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: '收入金额',
                    type: 'bar',
                    barWidth: '60%',
                    data: y1,
                    itemStyle:{

                            color:'green'

                    }
                },
                {
                    name: '支出金额',
                    type: 'bar',
                    barWidth: '60%',
                    data: y2,
                    itemStyle:{

                            color:'red'

                    }
                }
            ]
        });
        bar.on('click', function(params) {
            // 1. 获取点击数据
            const month = params.name;  // 格式应为 yyyyMM (如 202306)
            console.log('month 直接打印:', month);  // 应输出 "2023-01"
            console.log(`模板字符串打印: ${month}`); // 应输出 "模板字符串打印: 2023-01"
            const seriesName = params.seriesName;
            const value = params.value;
            console.log(`点击月份: ${month}, 系列: ${seriesName}, 值: ${value}`);
            // 2. 显示加载状态
           // $('#detailModal .modal-body').html('<div class="text-center py-4"><i class="fa fa-spinner fa-spin fa-2x"></i> 加载中...</div>');
            $('#detailModal').modal('show');

            // 3. AJAX 请求数据
            $.ajax({
                url: 'bill/listByMonth',  // 注意修正URL路径
                type: 'POST',              // 查询操作建议用GET
                data: {
                    yearMonth: month      // 参数名与后端Controller一致
                },
                dataType: 'json',
                success: function(response) {
                    // 4. 成功回调 - 渲染表格
                    if (response && response.length > 0) {
                        var htmlBill = renderBillTable(response);
                        $('#detailModal .modal-body').html(htmlBill);
                    } else {
                        $('#detailModal .modal-body').html(
                            '<div class="alert alert-info">本月无账单数据</div>'
                        );
                    }
                },
                error: function(xhr, status, error) {
                    // 5. 错误处理
                    console.error("请求失败:", status, error);
                    $('#detailModal .modal-body').html(
                        `<div class="alert alert-danger">
                    <i class="fa fa-exclamation-circle"></i>
                    数据加载失败: ${xhr.status} ${error}
                </div>`
                    );
                }
            });
        });
    }

    // 饼图——按月份
    function getPieChartByMonth(x, y1, y2) {
        var items1 = [];
        for (var i = 0; i < x.length; i++) {
            items1.push({
                value: y1[i],
                name: x[i]
            })
        }
        var items2 = [];
        for (var i = 0; i < x.length; i++) {
            items2.push({
                value: y2[i],
                name: x[i]
            })
        }
        console.log(items1)
        console.log(items2)
        // items =
        // [
        //     { value: 1048, name: 'Search Engine' },
        //     { value: 735, name: 'Direct' },
        //     { value: 580, name: 'Email' },
        //     { value: 484, name: 'Union Ads' },
        //     { value: 300, name: 'Video Ads' }
        //   ];
        var pie = echarts.init(document.getElementById('chartArea'));
        pie.clear();
        pie.setOption({
            title: {
                text: '月度统计报告/饼图',
                left: 'center',
                textStyle: {
                    fontSize: 12,
                    // 若字体名称中带有空格，需要使用 `"` 包围
                    fontFamily: 'Arial',
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: ['收入金额','支出金额']
            },
            series: [
                {
                    name: '收入金额',
                    type: 'pie',
                    radius: '55%',
                    center: ['30%', '60%'],
                    data: items1,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                },
                {
                    name: '支出金额',
                    type: 'pie',
                    radius: '55%',
                    center: ['70%', '60%'],
                    data: items2,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }

            ]
        })
    }
    function unique(arr){
        for(var i=0; i<arr.length; i++){
            for(var j=i+1; j<arr.length; j++){
                if(arr[i]==arr[j]){         //第一个等同于第二个，splice方法删除第二个
                    arr.splice(j,1);
                    j--;
                }
            }
        }
        return arr;
    }

    // 专门处理Java后端返回的日期格式
    function formatJavaDate(javaDate) {
        if (!javaDate) return '-';

        // 处理Java的日期字符串（可能是时间戳或ISO格式）
        try {
            // 如果是时间戳（毫秒）
            if (/^\d+$/.test(javaDate)) {
                const date = new Date(parseInt(javaDate));
                return date.toLocaleDateString();
            }
            // 如果是ISO格式（如"2023-06-15T00:00:00"）
            else if (javaDate.includes('T')) {
                const date = new Date(javaDate);
                return date.toLocaleDateString();
            }
            // 其他格式直接返回
            return javaDate;
        } catch (e) {
            console.error("日期格式化错误:", e);
            return javaDate; // 返回原始值
        }
    }

    function renderBillTable(bills) {
        // 1. 验证数据输入
        if (!Array.isArray(bills)) {
            console.error("Invalid bills data:", bills);
            return '<div class="alert alert-danger">数据格式错误</div>';
        }

        // 2. 处理空数据情况
        if (bills.length === 0) {
            return '<div class="alert alert-info">没有可显示的账单记录</div>';
        }

        // 3. 生成表格行
        var rows = bills.map(function(bill) {
            // 确保每条数据都有必要字段（ES5 用 || 替代 ??）
            var safeBill = {
                name: bill.name || '',
                cash: Number(bill.cash) || 0,
                payment: bill.payment || '',
                pdate: bill.pdate || '',
                ptype: bill.ptype || '',
                reason: bill.reason || '',
                relationship: bill.relationship || ''
            };

            // 确定金额显示样式
            var amountClass = safeBill.ptype.indexOf('支出') !== -1 ? 'text-danger' : 'text-success';

            // 用字符串拼接替代模板字符串
            return '<tr>' +
                '    <td>' + safeBill.name + '</td>' +
                '    <td class="' + amountClass + '">' + safeBill.cash.toFixed(2) + '</td>' +
                '    <td>' + safeBill.payment + '</td>' +
                '    <td>' + safeBill.pdate + '</td>' +
                '    <td>' + safeBill.ptype + '</td>' +
                '    <td>' + safeBill.reason + '</td>' +
                '    <td>' + safeBill.relationship + '</td>' +
                '</tr>';
        }).join('');

        // 4. 返回完整表格HTML（用字符串拼接替代模板字符串）
        return '<div class="table-responsive">' +
            '    <table class="table table-striped table-hover">' +
            '        <thead>' +
            '            <tr>' +
            '                <th>姓名</th>' +
            '                <th>金额</th>' +
            '                <th>支付方式</th>' +
            '                <th>日期</th>' +
            '                <th>收支类型</th>' +
            '                <th>事由</th>' +
            '                <th>关系</th>' +
            '            </tr>' +
            '        </thead>' +
            '        <tbody>' +
            '            ' + rows + '' +
            '        </tbody>' +
            '    </table>' +
            '</div>';
    }

    // 日期格式化辅助函数
    function formatDate(dateStr) {
        if (!dateStr) return '';
        try {
            const date = new Date(dateStr);
            return isNaN(date.getTime()) ? dateStr : date.toLocaleDateString('zh-CN');
        } catch (e) {
            console.error("Date format error:", e);
            return dateStr;
        }
    }

</script>